package com.atwisdom.star.interceptors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.util.JwtTokenMap;
import com.atwisdom.star.common.util.JwtUtils;
import com.atwisdom.star.common.util.SystemConstant;
import com.atwisdom.star.exception.pojo.BusinessException;
import com.atwisdom.star.respvo.UserAccountVo;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Desc： 拦截器 用户token校验
 * @Date: 2018/8/25
 */
@Component
public class AuthorityInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(AuthorityInterceptor.class);

    /**
     * JWT的签发者
     **/
    @Value("${jwt.secret}")
    private String jwtSecret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            String authHeader = request.getHeader("token");
            if (StringUtils.isBlank(authHeader)) {
                logger.error("验证失败, 签名验证不存在token为空。");
                throw new BusinessException("-2","签名验证不存在");
            } else {
                //验证JWT的签名
                int jwtStatus = JwtUtils.validateJWT(authHeader, jwtSecret);
                if (jwtStatus == SystemConstant.JWT_ERRCODE_OK) {
                    //获取到用户id
                    Claims claims = JwtUtils.parseJWT(authHeader, jwtSecret);
                    String userId = String.valueOf(claims.get("userId"));
                    if(userId==null || "".equalsIgnoreCase(userId)){
                        throw new BusinessException("-2","签名不正确");
                    }
                    String jwtToken = JwtTokenMap.getToken(userId);
                    if (null == jwtToken) {
                        throw new BusinessException("-2","用户已退出登录");
                    }
                    Object user = JwtTokenMap.getUser(jwtToken);
                    UserAccountVo userAccount  = JSONObject.parseObject(JSONObject.toJSONString(user), UserAccountVo.class);
                    request.setAttribute("loginUser", userAccount);
                    request.setAttribute("userId", userId);
                    return true;
                } else {
                    switch (jwtStatus) {
                        // 签名验证不通过
                        case SystemConstant.JWT_ERRCODE_FAIL:
                            logger.info("签名验证不通过");
                            throw new BusinessException("-2","签名验证不通过");
                        // 签名过期，返回过期提示码
                        case SystemConstant.JWT_ERRCODE_EXPIRE:
                            logger.info("签名过期");
                            throw new BusinessException("-2","签名过期");
                        default:
                            throw new BusinessException("-2","签名验证不通过");
                    }
                }
            }
        } else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
